import logging
import sys

from MBparkAPI import settings

import os

from jinja2 import PackageLoader, Environment, FileSystemLoader

BASE_DIR = settings.UTILS_DIR
env = Environment(loader=FileSystemLoader(BASE_DIR))  # 创建一个包加载器对象
Object_Path = "jinjia2TMS"

SAVE_DIR = "render"

tmp_pages = ["urls.py", "views.py", "sqlmap.py", ]

apps = [
    {"content": [
        {
            "urlname": "mytasks",
            "viewname": "mytask_list",
            "modename": "mytask_list",
            "session": False,
            "query": 2,  # 1.info 2.list 3.commoit
            "params": "{'id':'id'}",
            "null_params": "{}",
            "sql_title": "MYTASK_LIST",
            "sql": """Select t.* from aoa_task_list as t inner join aoa_task_user as tu on tu.task_recive_user_id=t.task_id inner join aoa_user as u on u.user_id=tu.task_recive_user_id where u.user_id={id}""",
            "remarks": "My Task List"
        }],
        "app_name": "task",
    }
]


def main():
    for app in apps:
        app_name = app.get("app_name")
        try:
            os.mkdir(os.path.join(os.path.join(settings.BASE_DIR, "app"), app_name))
        except Exception as e:
            pass
        for tmp_page in tmp_pages:
            template_file = os.path.join(settings.UTILS_TEMP_DIR, tmp_page)
            template = env.get_template("templates/{}".format(tmp_page))  # 获取一个模板文件
            tf = template.render(contents=app.get("content"), name=app_name)  # 渲染
            with open(os.path.join(settings.BASE_DIR, "app") + '/{}/{}'.format(app_name, tmp_page), "wb") as f:
                f.write(tf.encode("utf8"))


if __name__ == '__main__':
    main()
